package cn.highedu.controller;


import cn.highedu.bean.Beneficiary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

@RestController
public class AccountController {

    Logger logger = LoggerFactory.getLogger(AccountController.class);

    /** 受益人，测试使用 */
    private Beneficiary beneficiary;

    @PostMapping("/accounts/{accountId}/beneficiaries")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity<String> addBeneficiary(@PathVariable Long accountId,
                                         @RequestBody String beneficiaryName){
        logger.debug("添加受益人");
        // 创建新的受益人
        beneficiary = new Beneficiary();
        beneficiary.setName(beneficiaryName);
        beneficiary.setId(2L);
        beneficiary.setAccountId(accountId);
        // 返回新资源的URI
        String newBeneficiaryLocation =
                "/accounts/"+accountId+"/beneficiaries/"+beneficiary.getId();
        logger.debug("新资源的URI：{}", newBeneficiaryLocation);
        // 返回状态码201，以及新资源的URI
        return ResponseEntity.created(URI.create(newBeneficiaryLocation)).build();
    }

    @GetMapping("/accounts/{accountId}/beneficiaries/{beneficiaryId}")
    public Beneficiary getBeneficiary(@PathVariable Long accountId,
                               @PathVariable Long beneficiaryId){
        logger.debug("获取受益人 {} 的信息", beneficiaryId);
        // 返回受益人
        if (beneficiary == null){
            throw new RuntimeException("无此受益人");
        }
        return beneficiary;
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public void handleException(RuntimeException e){
        logger.error("发生异常：", e);
    }

    @DeleteMapping("/accounts/{accountId}/beneficiaries/{beneficiaryId}")
    public void deleteBeneficiary(@PathVariable Long accountId,
                           @PathVariable Long beneficiaryId){
        logger.debug("删除受益人 {} 的信息", beneficiaryId);
        // 删除受益人
        beneficiary = null;
    }
}
